const multer = require('multer')
const path = require('path')
const ResHandler = require('./ResHandler')
const mime = require('mime')
const resHandler = new ResHandler()
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.resolve(__dirname, '../public/images'))
  },
  filename: (req, file, cb) => {
    const { companyName } = req.body
    cb(null, companyName + '-' + Date.now() + '.' + mime.getExtension(file.mimetype))
  }
})
const limits = {
  files: 1,
  fileSize: 20000
}
const fileFilter = (req, file, cb) => {
  // 这个函数应该调用 `cb` 用boolean值来
  // 指示是否应接受该文件
  const acceptType = [ 'jpg', 'png', 'gif', 'svg', 'jpeg' ]
  const fileExt = mime.getExtension(file.mimetype)
  if(acceptType.includes(fileExt)) {
    // 接受这个文件，使用`true`，像这样:
    cb(null, true)
  } else {
    // 拒绝这个文件，使用`false`，像这样:
    cb(null, false)
    // 如果有问题，你可以总是这样发送一个错误:
    cb(new Error(`暂不支持上传${fileExt}的文件类型`))
  }
}
const upload = multer({ 
  storage: storage,
  limits,
  fileFilter
}).single('companyLogo')

module.exports = (req, res, next) => {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // 发生错误
      res.json(resHandler.errRes({ message: err?.message || 'Server Error' }))
    } else if (err) {
      // 发生错误
      res.json(resHandler.errRes({ message: err?.message || 'Server Error' }))
    } else {
      // 一切都好
      next()
    }
  })
}